#include <MQTTClient.h>
#include "app_mqtt.h"
#include "log.h"
#include <sys/syscall.h>  // 提供 syscall 宏
#include <unistd.h>       // 提供 pid_t 类型



static MQTTClient client;                                                           // MQTT客户端
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; // MQTT客户端连接选项
static MQTTClient_message pubmsg = MQTTClient_message_initializer;                  // MQTT客户端要发布的消息

// 接收消息的回调函数
static int (*recv_callback)(char *, int);

// 消息发布完成(客户端收到回执)回调函数
void delivered(void *context, MQTTClient_deliveryToken dt)
{
    log_debug("消息已成功发送");
}

// 接收到消息的回调函数
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    log_debug("收到消息: %s, 长度：%d, tid=%l", message->payload, message->payloadlen, syscall(SYS_gettid));
    int result = 0;
    // 如果设置了接收消息的回调函数，则调用回调函数处理消息
    if (recv_callback)
    {
        result = recv_callback(message->payload, message->payloadlen) == 0 ? 1 : 0;
    }

    // 释放消息
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);

    return result; // 1表示消息已成功处理 否则会出错
}

void connlost(void *context, char *cause)
{
    log_error("连接丢失, 原因：%s", cause);
}

int app_mqtt_init()
{
    // 创建MQTT客户端
    int result;
    if ((result = MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_create failed: %d\n", result);
        return -1;
    }

    // 设置回调函数
    if ((result = MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered)) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_setCallbacks failed: %d\n", result);
        MQTTClient_destroy(&client);

        return -1;
    }

    // 连接MQTT服务器
    if ((result = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_connect failed: %d\n", result);
        MQTTClient_destroy(&client);

        return -1;
    }

    // 订阅主题接收消息
    if ((result = MQTTClient_subscribe(client, TOPIC_PULL, QOS)) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_subscribe failed: %d\n", result);
        MQTTClient_disconnect(client, TIMEOUT);
        MQTTClient_destroy(&client);
        return -1;
    }

    return 0;
}

void app_mqtt_close()
{
    MQTTClient_disconnect(client, TIMEOUT);
    MQTTClient_destroy(&client);
}

int app_mqtt_sendMsg(char *data, int len)
{
    pubmsg.payload = data;
    pubmsg.payloadlen = len;
    pubmsg.qos = QOS;

    //  发布消息
    if (MQTTClient_publishMessage(client, TOPIC_PUSH, &pubmsg, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_publishMessage failed");
        return -1;
}

    return 0;
}

void app_mqtt_registerRecvCallback(int (*callback)(char *data, int len))
{
    recv_callback = callback;
}
